package com.controller;

import com.biz.IShopcarBiz;
import com.biz.IShopcarBizImpl;
import com.entity.Shopcar;
import com.entity.Userinfo;
import com.util.AjaxResult;
import com.util.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/shopcar")
public class ShopcarAction extends BaseController {

    @Autowired
    private IShopcarBiz biz;

    public IShopcarBiz getBiz() {
        return biz;
    }

    public void setBiz(IShopcarBiz biz) {
        this.biz = biz;
    }

    /**
     * 加入购物车
     * @param  shopcar
     */
    @RequestMapping("/addshopcar")
    @ResponseBody
    public String addShopcar(Shopcar shopcar, HttpSession sess){
        Userinfo user=(Userinfo)sess.getAttribute("loger");
        shopcar.setUid(user.getId());
        List<Shopcar> list=(biz.getByUidAndBid(user.getId(),shopcar.getBookid()));
        if(list==null || list.size()==0){
            //如果没有添加过这个图书，就增加一个
            biz.addShopcar(shopcar);
        } else{
            //如果购物车添加过这个图书就修改数量
            for(Shopcar car:list){
                int num= car.getNum()+shopcar.getNum();
                car.setNum(num);
                biz.modShopcar(car);
            }
        }
//        shopcar.setUid(5);
      return "success";
    }

    //登陆人的购物车列表
    @RequestMapping("/getShopcarByUid")
    public String  getShopcarByUid(HttpSession sess){
      Userinfo userinfo=(Userinfo)  sess.getAttribute("loger");
      List<Map> list=biz.getShopcarByUid(userinfo.getId());
      sess.setAttribute("carlist",list);
      return "cart";
    }

    //删除购物车
    @RequestMapping("/delShopcar")
    @ResponseBody
    public AjaxResult delShopcar(Integer id){
      return  toAjax(biz.delShopcar(id));
    }
}
